<template>
  <div class="intelligent_access_control">
    <van-nav-bar
      title="智能门禁"
      left-arrow
      @click-left="$router.go(-1)"
      fixed
    />
    <div class="repair_info">
      <van-field
        v-model="form.address"
        label="访问社区"
        placeholder="请选择访问社区"
        clearable
        readonly
        clickable
        @click="showPicker = true"
        right-icon="arrow"
        required
      />
      <van-field
        v-model="form.houseNumber"
        label="访问门牌号"
        placeholder="请选择访问门牌号"
        clearable
        readonly
        clickable
        @click="selectHouse"
        right-icon="arrow"
        required
      />
      <!-- <van-field
        v-model="form.houseNumber"
        label="访问门牌号"
        placeholder="请输入访问门牌号"
        clearable
        class="repair_input_box"
        required
      /> -->
      <van-field
        v-model="form.proprietorPhone"
        type="number"
        label="业主电话"
        placeholder="请输入业主电话"
        clearable
        maxlength="15"
        class="repair_input_box"
        required
      />
      <van-field
        v-model="form.visitorName"
        label="访客姓名"
        placeholder="请输入访客姓名"
        clearable
        class="repair_input_box"
        required
      />
      <van-field
        v-model="form.visitorPhone"
        type="number"
        label="访客电话"
        placeholder="请输入访客电话"
        clearable
        maxlength="15"
        class="repair_input_box"
        required
      />
      <van-field
        v-model="form.visitorDate"
        label="到访时间"
        placeholder="2019-08-29 17:00"
        clearable
        readonly
        clickable
        @click="timePicker = true"
        right-icon="arrow"
        required
      />
      <van-field
        v-model="form.reason"
        label="到访事宜"
        type="textarea"
        rows="1"
        placeholder="请输入到访事宜"
        clearable
        class="repair_input_box"
        required
        autosize
      />
      <div class="image_box">
        <div class="content_desc">访客头像</div>
        <van-uploader
          v-model="form.avatar"
          :max-count="1"
          class="img_upload_box"
          :before-read="beforeRead"
          :after-read="afterRead"
        />
      </div>
    </div>
    <van-button
      class="next_btn apply_btn"
      @click="submit()"
      :disabled="!disabled"
      >提交申请
    </van-button>
    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        show-toolbar
        :columns="columns"
        @cancel="showPicker = false"
        @confirm="onConfirm"
      />
    </van-popup>
    <van-popup v-model="showHousePicker" position="bottom">
      <van-picker
        show-toolbar
        :columns="houseColumns"
        @cancel="showHousePicker = false"
        @confirm="houseConfirm"
      />
    </van-popup>
    <van-popup v-model="timePicker" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="datetime"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="timePicker = false"
        @confirm="timeConfirm"
      />
    </van-popup>
    <van-popup v-model="showLoading">
      <van-loading color="#DC4630" />
    </van-popup>
  </div>
</template>

<script>
import util from "@/utils/util";
import houseService from "@/controller/myhouse.js";
import { validatePhoneNum } from "@/utils/validate";
import { notEmpty } from "../emptyTest";
import smartProperty from "@/controller/smartProperty.js";
import constant from "@/controller/constant.js";
import uploadService from "@/controller/mine.js";
export default {
  name: "intelligentAccessControl",
  data() {
    return {
      form: {
        address: "",
        proprietorPhone: "",
        visitorPhone: "",
        visitorName: "",
        houseNumber: "",
        visitorDate: "",
        reason: "",
        avatar: [],
        visitorImage: ""
      },
      showPicker: false,
      showHousePicker: false,
      timePicker: false,
      columns: [],
      houseColumns: [],
      minHour: 10,
      maxHour: 23,
      minDate: new Date(),
      maxDate: new Date(2049, 12, 31),
      currentDate: new Date(),
      showLoading: false,
      visitorDetail: {}
    };
  },
  computed: {
    disabled: function() {
      return (
        notEmpty(this.form.address) &&
        notEmpty(this.form.proprietorPhone) &&
        notEmpty(this.form.visitorPhone) &&
        notEmpty(this.form.visitorName) &&
        notEmpty(this.form.houseNumber) &&
        notEmpty(this.form.visitorDate) &&
        notEmpty(this.form.reason)
      );
    }
  },
  mounted() {
    this.userId = JSON.parse(localStorage.getItem("userInfo")).currentUser.id;
    this.getBoundHouseList(this.userId);
    if (this.$route.query.id) {
      this.visitorDetail = this.$route.query;
      this.form.address = this.visitorDetail.neighborhoodName;
      this.form.houseNumber = this.visitorDetail.houseNumber;
      this.form.proprietorPhone = this.visitorDetail.proprietorPhone;
      this.form.visitorName = this.visitorDetail.visitorName;
      this.form.visitorPhone = this.visitorDetail.visitorPhone;
      this.form.visitorDate = this.visitorDetail.visitorDate;
      this.form.reason = this.visitorDetail.reason;
      this.form.visitorImage = this.visitorDetail.visitorImage;
      if (this.visitorDetail.visitorImage) {
        this.form.avatar.push(this.visitorDetail.visitorImage);
      }
    }
  },
  methods: {
    getBoundHouseList(id) {
      houseService.community_user_house_user(id).then(res => {
        if (res.code === "0") {
          this.columns = [];
          if (!res.datas.length) {
            this.$toast("暂无绑定社区");
            return;
          }
          res.datas.forEach(e => {
            this.columns.push({
              value: {
                neighborhoodId: e.neighborhoodId,
                houseId: e.houseId
              },
              text: e.neighborhoodName
            });
          });
        } else {
          if (res && res.msg) {
            this.$toast(res.msg);
          } else {
            this.$toast(constant.unusualMsg);
          }
        }
      });
    },
    createRecord(data) {
      smartProperty.community_visitor_record(data).then(res => {
        if (res.code === "0") {
          this.$toast("新增成功");
          this.$router.go(-1);
        } else {
          if (res && res.msg) {
            this.$toast(res.msg);
          } else {
            this.$toast(constant.unusualMsg);
          }
        }
      });
    },
    changeRecord(data) {
      data.id = this.visitorDetail.id;
      smartProperty.community_visitor_record_edit(data).then(res => {
        if (res.code === "0") {
          this.$toast("修改成功");
          this.$router.go(-1);
        } else {
          if (res && res.msg) {
            this.$toast(res.msg);
          } else {
            this.$toast(constant.unusualMsg);
          }
        }
      });
    },
    submit() {
      if (
        !validatePhoneNum(this.form.proprietorPhone) ||
        !validatePhoneNum(this.form.visitorPhone)
      ) {
        this.$toast("请输入合法电话号码");
        return;
      }
      const data = {
        communityId: JSON.parse(localStorage.getItem("userInfo")).jiedaoId,
        neighborhoodId: this.form.neighborhoodId,
        houseNumber: this.form.houseNumber,
        proprietorPhone: this.form.proprietorPhone,
        visitorName: this.form.visitorName,
        visitorPhone: this.form.visitorPhone,
        visitorDate: this.form.visitorDate,
        reason: this.form.reason,
        visitorImage: this.form.visitorImage
      };
      if (this.$route.query.id) {
        this.changeRecord(data);
      } else {
        this.createRecord(data);
      }
    },
    selectHouse() {
      if (!this.form.address) {
        this.$toast('请先选择访问社区！')
        return
      }
      this.showHousePicker = true
    },
    getMyHouseList(id) {
      smartProperty.community_user_house_neighborhood_current(id).then(res => {
        this.showLoading = false
        this.houseColumns = []
        if (res.code === "0") {
          if (!res.datas.length) {
            this.$toast("暂无绑定房屋");
            return;
          }
          res.datas.forEach(e => {
            this.houseColumns.push({
              value: e.houseId,
              text: e.houseName
            });
          });
        } else {
          if (res && res.msg) {
            this.$toast(res.msg);
          } else {
            this.$toast(constant.unusualMsg);
          }
        }
      }).catch(() => {
        this.showLoading = false
      })
    },
    onConfirm(val) {
      this.showPicker = false;
      this.form.address = val.text;
      this.form.neighborhoodId = val.value.neighborhoodId;
      this.showLoading = true
      this.getMyHouseList(val.value.neighborhoodId)
    },
    houseConfirm(val) {
      this.showHousePicker = false;
      this.form.houseNumber = val.text;
      this.form.houseId = val.houseId;
    },
    timeConfirm(val) {
      this.timePicker = false;
      this.form.visitorDate = util.formatDate.format(
        val,
        "yyyy/MM/dd hh:mm:ss"
      );
    },
    beforeRead(file) {
      const acceptImgs = ["image/jpeg", "image/png", "image/jpg"];
      if (!acceptImgs.includes(file.type)) {
        this.$toast("请上传JPG或者PNG格式的图片!");
        return false;
      }
      this.showLoading = true;
      return true;
    },
    afterRead(file) {
      let formData = new FormData();
      formData.append("file", file.file);
      uploadService
        .upload_image(formData)
        .then(res => {
          if (res.data.code === "0") {
            this.$toast("图片上传成功！");
            this.form.visitorImage = res.data.datas;
            this.visitorDetail.visitorImage = res.data.datas;
          } else {
            if (res && res.data && res.data.msg) {
              this.$toast(res.data.msg);
            } else {
              this.$toast(constant.unusualMsg);
            }
          }
        })
        .catch(() => {})
        .then(() => {
          this.showLoading = false;
        });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "../styles/workstation.scss";

.intelligent_access_control {
  height: 100%;
  background: #ffffff;
  .repair_info {
    display: flex;
    flex-wrap: wrap;
  }

  .image_box {
    padding: 10px 15px 0;
    border-bottom: 1px solid rgba(226, 226, 226, 0.5);

    .content_desc {
      line-height: 20px;
      font-size: 14px;
      color: #333333;
      width: 230px;
      word-break: break-all;
      float: left;
    }

    .img_upload_box {
      float: right;
    }
  }

  .image_box::after {
    content: "\20";
    display: block;
    height: 0;
    clear: both;
  }

  .image_box::before {
    position: absolute;
    left: 0.21333rem;
    color: #ff4444;
    font-size: 0.37333rem;
    content: "*";
  }
}
</style>

<style lang="scss">
.intelligent_access_control {
  .image_box {
    .van-uploader__preview-image {
      width: 107px;
      height: 82px;

      .van-image__error,
      .van-image__img,
      .van-image__loading {
        border-radius: 5px;
      }
    }

    .van-uploader__upload {
      width: 107px;
      height: 82px;
      border-radius: 5px;
      border-style: solid;
      background-color: #f5f7fa;
    }

    .van-uploader__upload-icon {
      font-size: 25px;
    }
  }

  .van-tabs__line {
    background-color: #dc4630;
    width: 187.5px !important;
    height: 2px;
  }

  .van-ellipsis {
    font-size: 14px;
  }

  .van-cell {
    font-size: 14px;
    line-height: 20px;
    padding: 10px 15px;
  }

  .van-cell:first-child {
    padding-top: 15px;
  }

  .van-field__control {
    text-align: right;
    font-size: 14px;
  }

  .repair_input_box {
    .van-field__control {
      margin-right: 24px;
    }
  }
}
</style>
